const IP = "192.168.1.103";
// const IP = "47.107.190.107";
const SUCCESS = 0;
const ERROR_MAKE_ORDER_NOT_MATCH = 7109;//没找到匹配的档位

const PAY_WX = 1;
const PAY_ALI = 2;

const TEXT_WX = "微信二维码，请使用微信扫码或者保存图片使用扫一扫从相册中识别";
const TEXT_ALI = "支付宝二维码，请使用支付宝扫码或者保存图片使用扫一扫从相册中识别";

let m_user = '';
let m_listPayItem = [];
let m_payItem = null;
let m_payType = 0;  //1：微信   2：支付宝
let m_qrcodeId = '';
let m_nTimer;
let m_recieveMoney = null;
// showPayItem();

function showAlert(errorMsg) {
    alert(errorMsg);
    $("#id_div_loading").css("display","none");
}

/**
 * 对外调用的接口（Android）
 * @param user
 * @constructor
 */
function InterfaceSetUser(data) {
    let dataOject = JSON.parse(data);
    let user = dataOject['user'];
    let money = dataOject['money'];
    if(typeof (user) != 'undefined' && user != '') {
        $(".class_user_input").val(user)
        m_recieveMoney = money;
        checkUser(user);
    }
}

function checkUser(user) {
    $("#id_div_loading").css("display","block");
    var url = 'http://{0}/thinkphp/Sample_Mjmz/Pay/checkUserWeb?userName={1}'.format(IP,user);
    $.ajax({
        type:"GET",
        url:url,
        dataType:'json',
        success:function (result) {
            $("#id_div_loading").css("display","none");
            m_user = user;
            if(result['status'] == SUCCESS) {
                $(".class_user_result").html("校验成功").css("color","green");
                if(result['data'] == -1) {
                    //没有匹配到有效订单
                    showPayItem();
                }else {
                    $("#id_div_user").css("display","none");
                    $("#id_div_qrcode").css("display","block");
                    showQrcodePage(result['data']);
                }
            }else {
                $(".class_user_result").html("用户名不存在").css("color","red");
            }
        },
        error:function (errorMsg) {
            showAlert('网络异常,请重试！')
        }
    });
}

function btnNextClick() {
    var user = $(".class_user_input").val();
    checkUser(user);
}

function showPayItem() {
    $("#id_div_user").css("display","none");
    $("#id_div_selected").css("display","block");
    var url = 'http://{0}/thinkphp/Sample_Mjmz/Pay/getPayItem'.format(IP);
    $.ajax({
        type:"GET",
        url:url,
        dataType:'json',
        success:function (result) {
            if(result['status'] == SUCCESS) {
                var  html = '';
                m_listPayItem = result['data'];
                if(m_recieveMoney != null) {
                    let isFind = false;
                    for(let i = 0 ; i < m_listPayItem.length ; i++) {
                        if(m_listPayItem[i]['money'] == m_recieveMoney) {
                            m_payItem = m_listPayItem[i];
                            isFind = true;
                            break;
                        }
                    }
                    if(isFind) {
                        $("#id_div_wx_alipay").css("display","block");
                        $("#id_div_selected").css("display","none");
                    }
                }else {
                    for(var i = 0 ; i < m_listPayItem.length ; i++) {
                        let  object = m_listPayItem[i];
                        var  tip = object['description'];
                        var  chargeText = '充值￥' + object['money']/100.0;
                        html += ' <li>\n' +
                            '                    <span>\n' +
                            '                        <img src="resource/image/icon_gold_coin.png">\n' +
                            '                        <font>{0}</font>\n'.format(tip) +
                            '                    </span>\n' +
                            '                    <button id = {0} onclick="chargeBtnClicked(this)">{1}</button>\n'.format(i,chargeText) +
                            '                </li>';

                        $(".class_selected_ul").html(html);
                    }
                }
            }else {
                showAlert('网络异常,请重试！');
            }
        },
        error:function (errorMsg) {
            showAlert('网络异常,请重试！');
        }
    });
}

function chargeBtnClicked(elementObject) {
    let index = elementObject.getAttribute('id');
    m_payItem = m_listPayItem[index];
    $("#id_div_wx_alipay").css("display","block");
    $("#id_div_selected").css("display","none");
}

/**
 * 显示二维码页面
 * @param data
 */
function showQrcodePage(objectJson) {
    m_qrcodeId = objectJson['qrcode_id'];
    m_payType = objectJson['pay_type'];

    let element = $(".class_qrcode_tip");
    if(objectJson['pay_type'] == PAY_WX) {
        element.html(TEXT_WX);
    }else {
        element.html(TEXT_ALI);
    }

    $(".class_qrcode_img").attr("src",objectJson['qrcode_url']);
    $(".class_qrcode_description").html('{0} ￥{1}'.format(objectJson['description'],objectJson['real_money']/100.0));
    $(".class_qrcode_time").html(objectJson['expiry_time']);

    let image = new Image();
    image.src = objectJson['qrcode_url'];
    image.onload = function () {
        let base64 = getBase64Image(image);
        let file = dataURLtoFile(base64);
        qrcode.decode(getObjectURL(file));
        qrcode.callback = function (imgMsg) {
            //调用java方法
            if(typeof (window.payJava) != 'undefined') {
                objectJson['qrcode_content'] = imgMsg;
                window.payJava.JsQrcodePageShow(JSON.stringify(objectJson));
            }
            //倒计时
            m_nTimer = setInterval(function () {
                let nowTime = getNowFormatDate();
                let time = comptime(nowTime,objectJson['expiry_time']);
                if(time <= 0) {
                    //过了有效期
                    $("#id_div_qrcode").css("display","none");
                    $("#id_div_cancel").css("display","block");
                    $(".class_cancel_tip").html("已过期,订单自动取消");
                    clearInterval(m_nTimer);
                    cancelQrcode();
                }
            },1000);
        }
    };
}

/**
 * 获取当前时间
 * @returns {string}
 */
function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
        + " " + date.getHours() + seperator2 + date.getMinutes()
        + seperator2 + date.getSeconds();
    return currentdate;
}

/**
 * yyyy-mm-dd hh:mi:ss
 * @param beginTime
 * @param endTime
 * @returns 0:相等  1：大于  -1:小于
 */
function comptime(beginTime,endTime) {
    var beginTimes = beginTime.substring(0, 10).split('-');
    var endTimes = endTime.substring(0, 10).split('-');

    beginTime = beginTimes[1] + '-' + beginTimes[2] + '-' + beginTimes[0] + ' ' + beginTime.substring(10, 19);
    endTime = endTimes[1] + '-' + endTimes[2] + '-' + endTimes[0] + ' ' + endTime.substring(10, 19);

    var a = (Date.parse(endTime) - Date.parse(beginTime)) / 3600 / 1000;
    return a;
}

function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, img.width, img.height);
    var dataURL = canvas.toDataURL("image/png");
    return dataURL
    // return dataURL.replace("data:image/png;base64,", "");
}

function dataURLtoFile(dataurl) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {type:mime});
}

var getObjectURL = function(file){
    var url = null ;
    if (window.createObjectURL!=undefined) { // basic
        url = window.createObjectURL(file) ;
    } else if (window.URL!=undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file) ;
    } else if (window.webkitURL!=undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file) ;
    }
    return url ;
}

function payBtnClicked(payType) {
    $("#id_div_loading").css("display","block");
    m_payType = payType;
    //下订单
    var url = 'http://{0}/thinkphp/Sample_Mjmz/Pay/makePayOrderWeb'.format(IP);
    $.ajax({
        type:"GET",
        data:{
            userName: m_user,
            payType: m_payType,
            coin: m_payItem['coin'],
            money: m_payItem['money'],
            platform: 3,            //Web端
        },
        url:url,
        dataType:'json',
        success:function (result) {
            $("#id_div_loading").css("display","none");
            if(result['status'] == SUCCESS) {
                let objectJson = result['data'];
                objectJson['pay_type'] = m_payType;
                objectJson['description'] = m_payItem['description'];

                $("#id_div_qrcode").css("display","block");
                $("#id_div_wx_alipay").css("display","none");

                showQrcodePage(objectJson);
            }else if(result['status'] == ERROR_MAKE_ORDER_NOT_MATCH){
                showAlert('没找到匹配的档位！');
            }else {
                showAlert('网络异常，请重试！')
            }
        },
        error:function (errorMsg) {
            $("#id_div_loading").css("display","none");
            showAlert('网络异常,请重试！')
        }
    });
}

/**
 * 取消订单
 */
function cancelQrcode() {
    $("#id_div_loading").css("display","block");
    var url = 'http://{0}/thinkphp/Sample_Mjmz/Pay/cancelQrcodeWeb'.format(IP);
    $.ajax({
        type:"GET",
        data:{
            userName:m_user,
            qrcodeId:m_qrcodeId,
        },
        url:url,
        dataType:'json',
        success:function (result) {
            $("#id_div_loading").css("display","none");
            if(result['status'] == SUCCESS) {
                $("#id_div_qrcode").css("display","none");
                $("#id_div_cancel").css("display","block");
            }else {
                showAlert('取消订单失败！')
            }
        },
        error:function (errorMsg) {
            showAlert('网络异常,请重试！')
        }
    });
}